package com.intramirror.wd.business.manage.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.intramirror.common.base.model.ApiResponse;
import com.intramirror.wd.business.manage.CouponStrategyManage;
import com.intramirror.wd.business.mapper.S2cCouponStrategyMapper;
import com.intramirror.wd.business.mapper.S2cCouponStrategyRelMapper;
import com.intramirror.wd.business.mapper.S2cCouponsMapper;
import com.intramirror.wd.business.util.ChucResponse;
import com.intramirror.wd.business.util.CollectionUtil;
import com.intramirror.wd.business.util.CopyUtil;
import com.intramirror.wd.model.po.S2cCouponStrategy;
import com.intramirror.wd.model.po.S2cCouponStrategyRel;
import com.intramirror.wd.model.po.S2cCoupons;
import com.intramirror.wd.model.vo.page.PageVo;
import com.intramirror.wd.model.vo.coupon.S2cCouponStrategyVo;

/**
 * Created by juzhongzheng on 2018/4/27.
 */
@Service
public class CouponStrategyManageImpl implements CouponStrategyManage {

    @Autowired
    private S2cCouponStrategyMapper strategyMapper;
    @Autowired
    private S2cCouponStrategyRelMapper stategyRelMapper;
    @Autowired
    private S2cCouponsMapper couponsMapper;


    public static void main(String[] args) {
        S2cCouponStrategyVo s2cCouponStrategyVo = new S2cCouponStrategyVo();
        Gson gson = new Gson();
        String json = gson.toJson(s2cCouponStrategyVo);
        System.out.println(json);
        System.out.println(new Date());
    }


    @Override
    @Transactional
    public Object saveCouponStrategy(S2cCouponStrategyVo strategyVo) {
        if(strategyVo.getName() == null || strategyVo.getStartDate() == null || strategyVo.getEndDate() == null || strategyVo.getType() == null) {
            return new ChucResponse<>("parameter missing");
        }
        S2cCouponStrategy strategy = new S2cCouponStrategy();
        Date date = new Date();
        strategy.setCreatedAt(date);
        strategy.setUpdatedAt(date);
        strategy.setName(strategyVo.getName());
        strategy.setRemark(strategyVo.getRemark());
        strategy.setStartDate(strategyVo.getStartDate());
        strategy.setEndDate(strategyVo.getEndDate());
        strategy.setType(strategyVo.getType());
        strategy.setFetchType(strategyVo.getFetchType());
        Long id = strategyMapper.insertSelective(strategy);
        if(id == 0) {
            return new ApiResponse<>("insert CouponStrategy error");
        }

        List<Integer> couponIds = strategyVo.getCouponIds();
        if(CollectionUtils.isEmpty(couponIds)) return 0;

        return insertBatchStrategyRel(couponIds, strategy.getId().intValue());
    }

    @Transactional
    public Object insertBatchStrategyRel(List<Integer> couponIds, Integer id) {
        if(CollectionUtil.isEmpty(couponIds)) {
            return new ChucResponse<>(true);
        }
        List<S2cCouponStrategyRel> stategyRelList = new ArrayList<>(couponIds.size());
        Date date1 = new Date();
        for (int i = 0; i < couponIds.size(); i++) {
            S2cCouponStrategyRel rel = new S2cCouponStrategyRel();
            rel.setStrategyId(id);
            rel.setCouponId(couponIds.get(i));
            rel.setCreatedAt(date1);
            rel.setUpdatedAt(date1);
            stategyRelList.add(rel);
        }
        int i = stategyRelMapper.insertList(stategyRelList);
        if(i <= 0) {
            return new ChucResponse<>("insert StrategyRel error");
        }
        return new ChucResponse<>(true);
    }


    @Override
    @Transactional
    public Object updateCouponStrategy(S2cCouponStrategyVo strategyVo, Long id) {

        S2cCouponStrategy strategy = CopyUtil.copy(strategyVo, S2cCouponStrategy.class);

        strategy.setFetchType(strategyVo.getFetchType());
        strategy.setType(strategyVo.getType());
        strategy.setUpdatedAt(new Date());
        strategy.setId(id);
        strategyMapper.updateByPrimaryKeySelective(strategy);
        S2cCouponStrategy couponStrategy = strategyMapper.selectByPrimaryKey(id);
        if(null == couponStrategy) {
            return new ApiResponse<>("couponStrategy is null");
        }
        stategyRelMapper.deleteByStrategyId(id.intValue());
        List<Integer> couponIds = strategyVo.getCouponIds();
        if(CollectionUtils.isEmpty(couponIds)) {
            return new ApiResponse<>("couponIds is null");
        }
        return  insertBatchStrategyRel(couponIds, id.intValue());
    }

    @Override
    @Transactional
    public Object delCouponStrategy(Long id) {
        int i = strategyMapper.deleteById(id);
        if (i <= 0) {
            return new ChucResponse<>("delete error");
        }
        //关联表
        stategyRelMapper.deleteByStrategyId(id.intValue());
        return new ChucResponse<>(true);
    }

    @Override
    public PageVo<S2cCouponStrategyVo> getAllStrategy(S2cCouponStrategyVo vo) {
        PageVo<S2cCouponStrategyVo> pageResultVO = new PageVo<>();

        List<S2cCouponStrategyVo> couponStrategyList = strategyMapper.getCouponStrategyList();

        //总数
        couponStrategyList.forEach(e -> {
            List<S2cCoupons> collect = e.getCouponsList();
            List<S2cCoupons> couponsList = collect.stream().filter(h -> h.getTotalCount() != null || h.getCount() != null).collect(Collectors.toList());
            int sum = couponsList.stream().mapToInt(S2cCoupons::getTotalCount).sum();
            int restSum = couponsList.stream().mapToInt(S2cCoupons::getCount).sum();
            e.setSum(sum);
            e.setRestSum(restSum);
        });
        //剩余数量

        if (CollectionUtil.isEmpty(couponStrategyList)) {
            return null;
        }

        pageResultVO.setCount(couponStrategyList.size());
        pageResultVO.setList(couponStrategyList);
        pageResultVO.setPage(vo.getPage());
        pageResultVO.setPageSize(vo.getPageSize());
        return pageResultVO;
    }

    @Override
    public S2cCouponStrategyVo getStrategySetailById(Long id) {
        
        S2cCouponStrategy s2cCouponStrategy = strategyMapper.selectByPrimaryKey(id);

        if(null == s2cCouponStrategy) {
            return null;
        }

        S2cCouponStrategyVo copyVo = CopyUtil.copy(s2cCouponStrategy, S2cCouponStrategyVo.class);

        List<S2cCouponStrategyRel> relList = stategyRelMapper.findByStrategyId(s2cCouponStrategy.getId());

        List<Integer> couponIdList = CollectionUtil.toList(relList, S2cCouponStrategyRel::getCouponId);

        if (CollectionUtil.isNotEmpty(couponIdList)) {
            List<S2cCoupons> couponsList = couponsMapper.findByIdIn(couponIdList);
            copyVo.setCouponsList(couponsList);
        }
        return copyVo;
    }

    @Override
    public Object changeIsPublish(Long id, Integer flag) {
        S2cCouponStrategy strategy = new S2cCouponStrategy();
        strategy.setId(id);
        strategy.setIsPublished(flag);
        int key = strategyMapper.updateByPrimaryKeySelective(strategy);
        if(key <= 0) {
            return new ChucResponse<>(" update isPublish error");
        }
        return new ChucResponse<>(true);
    }

    @Override
    public Object getIsPublishedStrategy(Integer isPublished) {
        List<S2cCouponStrategy> strategyList = strategyMapper.findByIsPublished(isPublished);

        return CollectionUtil.toList(strategyList, S2cCouponStrategy::getName);
    }


}
